package com.lbd;

import java.util.*;
import java.util.concurrent.TimeUnit;

public class TestPool {

    /**
     * <cityCode,User>
     */
    private static Map<Integer, List<User>> map;
    //模拟用户
    private static List<User> users = new ArrayList<>();

    TestPool() {
        //模拟用户
        for (int i = 1; i <= 25; i++) {
            User user = new User();
            user.setCityCode(Integer.valueOf("59" + (i % 10)));
            user.setName("person" + i);
            users.add(user);
        }
        //591-595三次，590，596-599两次
    }

    //业务模拟：将相同地市的用户添加到一个集合下
    public void handle() {
        //从对象池获取map
        map = ObjectPool.getMapListBasicCDN();
        try {
            users.forEach(user -> map.computeIfAbsent(user.getCityCode(), key -> ObjectPool.getListBasicCdnObj()).add(user));
            System.out.println(map.toString());
        } finally {
            //归还map中的List对象
            for (Map.Entry<Integer, List<User>> basicCDNS : map.entrySet()) {
                List<User> userList = basicCDNS.getValue();
                ObjectPool.offerListBasicCdnObj(userList);
                basicCDNS.setValue(null);
            }
            //归还map
            ObjectPool.offerMapListBasicCDN(map);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TestPool testPool = new TestPool();

        testPool.handle();

        TimeUnit.SECONDS.sleep(2);
        ObjectPool.getSize();

        testPool.handle();

        while (true) {
            TimeUnit.SECONDS.sleep(2);
            ObjectPool.getSize();
        }
    }
}
